// 获取页面元素
const videoPlayer = document.getElementById('videoPlayer');
const videoUrl = document.getElementById('videoUrl');
const playButton = document.getElementById('playButton');
const status = document.getElementById('status');

// 检查是否支持 HLS
function isHlsSupported() {
    return Hls.isSupported();
}

// 创建 HLS 实例并加载视频
function loadHlsVideo(url) {
    const hls = new Hls();
    hls.loadSource(url);
    hls.attachMedia(videoPlayer);
    hls.on(Hls.Events.MANIFEST_PARSED, () => {
        videoPlayer.play().then(() => {
            showStatus('视频加载成功', 'success');
        }).catch(error => {
            showStatus(`播放失败: ${error.message}`, 'error');
        });
    });

    hls.on(Hls.Events.ERROR, (event, data) => {
        if (data.fatal) {
            showStatus(`HLS 错误: ${data.type}`, 'error');
        }
    });
}

// 判断是否是 m3u8 格式
function isM3u8(url) {
    return url.toLowerCase().includes('.m3u8');
}

// 播放按钮点击事件处理
playButton.addEventListener('click', () => {
    const url = videoUrl.value.trim();
    
    // 验证URL是否为空
    if (!url) {
        showStatus('请输入视频链接', 'error');
        return;
    }

    try {
        if (isM3u8(url)) {
            // 处理 m3u8 格式
            if (isHlsSupported()) {
                loadHlsVideo(url);
            } else if (videoPlayer.canPlayType('application/vnd.apple.mpegurl')) {
                // Safari 原生支持 HLS
                videoPlayer.src = url;
                videoPlayer.play().then(() => {
                    showStatus('视频加载成功', 'success');
                }).catch(error => {
                    showStatus(`播放失败: ${error.message}`, 'error');
                });
            } else {
                showStatus('您的浏览器不支持 HLS 播放', 'error');
            }
        } else {
            // 处理普通视频格式
            videoPlayer.src = url;
            videoPlayer.load();
            videoPlayer.play().then(() => {
                showStatus('视频加载成功', 'success');
            }).catch(error => {
                showStatus(`播放失败: ${error.message}`, 'error');
            });
        }
    } catch (error) {
        showStatus(`错误: ${error.message}`, 'error');
    }
});

// 显示状态信息
function showStatus(message, type) {
    status.textContent = message;
    status.className = type;
}

// 视频错误处理
videoPlayer.addEventListener('error', () => {
    showStatus('视频加载失败，请检查链接是否正确', 'error');
}); 